//
//  STSignInInputPwdView.swift
//  iPhone
//
//  Created by Toj on 4/19/23.
//

import UIKit

class STSignInInputPwdView: UIView {
    
     let hasPrebingCard = arc4random_uniform(2) == 1
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupMakeAddSubviews()
        setupMakeInitialize()
        setupMakeNotification()
        setupMakeLayoutSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /* 背景View */
    private lazy var backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.tt_alpha(0.5)
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(didTapBackground))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    /* 展示内容 */
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        view.cm_corner(radius: 24, corners: [.layerMinXMinYCorner, .layerMaxXMinYCorner])
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(didTapEndEditing))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    /* 返回按钮 */
    private lazy var backButton: UIButton = {
        let view = UIButton()
        view.setImage("com_signin_back_icon".img_resource, for: .normal)
        view.addTarget(self, action: #selector(didTapClosed), for: .touchUpInside)
        return view
    }()
    
    /* 标题 */
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.textColor = "#333333".to_color
        view.font = 20.to_boldFont
        view.textAlignment = .center
        view.numberOfLines = 0
        view.text = "NewSignIn_title3".localized()
        return view
    }()
    
    /* 选择国家 */
    private(set) lazy var countryImageView = UIImageView()
    private lazy var arrowImageView: UIImageView = {
        let view = UIImageView()
        view.image = "com_arrow_down".img_resource
        return view
    }()
    private lazy var countryButton: UIButton = {
        let view = UIButton()
        view.addTarget(self, action: #selector(didTapSelectedCountry), for: .touchUpInside)
        return view
    }()
    
    /* 账号 */
    private(set) lazy var accountLabel: UILabel = {
        let view = UILabel()
        view.textColor = .black
        view.font = 14.to_boldFont
        return view
    }()
    
    /* account Line */
    private lazy var accountLineView: UIView = {
        let view = UIView()
        view.backgroundColor = "#999999".to_color
        return view
    }()
    
    /* 密码图标 */
    private lazy var passwordIcon: UIImageView = {
        let view = UIImageView()
        view.image = "com_password_icon".img_resource
        return view
    }()
    
    /* 密码文本框 */
    private lazy var passwordTextField: UITextField = {
        let view = UITextField()
        let ptext = "password".localized()
        let attributedPlaceholder = ptext.to_attributedString(font:  UIFont.systemFont(ofSize: 14), color: "#DDDDDD".to_color)
        view.attributedPlaceholder = attributedPlaceholder
        view.textColor = .black
        view.font = 16.to_boldFont
        // view.clearsOnBeginEditing = true
        view.keyboardType = .default
        // 清空按钮
        view.clearButtonMode = .whileEditing
        view.backgroundColor = .clear
        // 边框
        view.borderStyle = .none
        // 是否纠错
        view.autocorrectionType = .no
        // 首字母大写
        view.autocapitalizationType = .none
        
        view.delegate = self
        return view
    }()
    
    /* 查看密码 */
    private lazy var displayButton: UIButton = {
        let view = UIButton()
        view.setImage("com_pwd_see_normal".img_resource, for: UIControl.State.normal)
        view.setImage("com_pwd_see_selected".img_resource, for: UIControl.State.selected)
        view.addTarget(self, action: #selector(didTapDisplay(sender:)), for: .touchUpInside)
        return view
    }()
   
    /* password Line */
    private lazy var passwordLineView: UIView = {
        let view = UIView()
        view.backgroundColor = "#999999".to_color
        return view
    }()
    
    /* 账号 */
    private lazy var prebindingCardLabel: UILabel = {
        let view = UILabel()
        view.text = "prebindingCard".localized()
        view.textColor = "#AAAAAA".to_color
        view.font = 12.to_boldFont
        return view
    }()
   
    /* 忘记密码*/
    private lazy var forgotButton: UIButton = {
        let view = UIButton()
        let attributedTitle = "forget_password".localized().to_attributedString(font: 14.to_boldFont, lineStyle: .underline)
        view.setAttributedTitle(attributedTitle, for: .normal)
        view.sizeToFit()
        view.addTarget(self, action: #selector(didTapForgot), for: .touchUpInside)
        return view
    }()
    
    /* 登录按钮 */
    private lazy var signInButton: UIButton = {
        let view = UIButton()
        view.backgroundColor = "#0087EB".to_color
        view.titleLabel?.font = 14.to_boldFont
        view.setTitleColor(.white, for: .normal)
        view.setTitle("NewSignIn_title1".localized(), for: .normal)
        let width = CGFloat.sr_width - 80
        view.frame = CGRect(origin: .zero, size: CGSize(width: width, height: 32.ui_scale))
        view.addTarget(self, action: #selector(didTapSignin), for: .touchUpInside)
        view.cm_cornerRadius = 16.ui_scale
        return view
    }()
    
    private lazy var privacyView: STSignInPrivacyView = {
        let view = STSignInPrivacyView()
        return view
    }()
}

// MARK: - 点击事件
@objc private extension STSignInInputPwdView {
    
    func didTapSelectedCountry() {
        print("-->shantao: func:" + #function)
        dismiss()
    }
    
    func didTapClosed() {
        print("-->shantao: func:" + #function)
        didTapEndEditing()
        dismiss()
    }
    
    func didTapSignin() {
        print("-->shantao: func:" + #function)
        didTapEndEditing()
    }
    
    func didTapDisplay(sender: UIButton) {
        print("-->shantao: func:" + #function)
        sender.isSelected = !sender.isSelected
        passwordTextField.isSecureTextEntry = sender.isSelected
    }
    
    func didTapForgot() {
        print("-->shantao: func:" + #function)
        didTapEndEditing()
    }
    
    func didTapBackground() {
        didTapEndEditing()
        dismiss()
    }
    
    func didTapEndEditing() {
        endEditing(true)
    }
    
    func keyboardWillShow(notification: Notification) {
        guard let info = notification.userInfo as NSDictionary?
        else { return }
        
        let frameValue = info[UIResponder.keyboardFrameEndUserInfoKey]
        // 得到键盘frame
        let keyboardFrame = (frameValue as AnyObject).cgRectValue
        let kbHeight = keyboardFrame?.size.height ?? 303
        
        let kbDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey]
        let duration = kbDuration as? TimeInterval ?? 0.25
        
        setupMakeLayoutContentView(bottom: kbHeight, isShowKeyboard: true)
        
        UIView.animate(withDuration: duration) {
            self.layoutIfNeeded()
        }
    }
    
    func keyboardWillHide(notification: Notification) {
        guard let info = notification.userInfo as NSDictionary?
        else { return }
        
        let kbDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey]
        let duration = kbDuration as? TimeInterval ?? 0.25
        
        setupMakeLayoutContentView()
        
        UIView.animate(withDuration: duration) {
            self.layoutIfNeeded()
        }
    }
}

// MARK: - Public
extension STSignInInputPwdView {
    
    func show() {
        clearAccount()
        isHidden = false
        setNeedsLayout()
    }
    
    func dismiss() {
        isHidden = true
        removeFromSuperview()
    }
}

// MARK: - Private
private extension STSignInInputPwdView {
    
    func clearAccount() {
        
    }
}

extension STSignInInputPwdView: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        didTapSignin()
        
        return true
    }
}

// MARK: - 初始化设置
private extension STSignInInputPwdView {
    
    func setupMakeAddSubviews() {
        
        addSubview(backgroundView)
        
        addSubview(contentView)
        
        // 标题
        contentView.addSubview(titleLabel)
        // 关闭按钮
        contentView.addSubview(backButton)
        // 国家
        contentView.addSubview(countryImageView)
        contentView.addSubview(arrowImageView)
        contentView.addSubview(countryButton)
        
        // 账号
        contentView.addSubview(accountLabel)
        // 账号下面的横线
        contentView.addSubview(accountLineView)
        
        // 密码图标
        contentView.addSubview(passwordIcon)
        // 密码文本框
        contentView.addSubview(passwordTextField)
        // 查看密码
        contentView.addSubview(displayButton)
        // password Line
        contentView.addSubview(passwordLineView)
        // 预绑卡状态提示
        contentView.addSubview(prebindingCardLabel)
        
        // 登录按钮
        contentView.addSubview(signInButton)
        // 忘记密码
        contentView.addSubview(forgotButton)
        // 服务协议
        contentView.addSubview(privacyView)
    }
    
    func setupMakeLayoutContentView(bottom margin: CGFloat = 0, isShowKeyboard: Bool = false) {
        let bottom = isShowKeyboard ? margin : 0
        print("-->shantao: margin:\(margin), is: \(isShowKeyboard)")
        let height = hasPrebingCard ? 390 : 360
        contentView.snp.remakeConstraints { make in
            make.left.right.equalTo(self)
            make.height.equalTo(height.ui_mscale)
            make.bottom.equalTo(-bottom)
        }
    }
    
    func setupMakeLayoutSubviews() {
        
        backgroundView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        setupMakeLayoutContentView()
        backButton.snp.makeConstraints { make in
            make.left.top.equalTo(contentView)
            make.width.equalTo(48)
            make.height.equalTo(48)
        }
        titleLabel.snp.makeConstraints { make in
            make.left.right.equalTo(contentView).inset(20)
            make.top.equalTo(contentView)
            make.height.equalTo(100.ui_mscale)
        }
        
        countryButton.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.width.equalTo(48)
            make.height.equalTo(30)
            make.top.equalTo(titleLabel.snp.bottom)
        }
        countryImageView.snp.makeConstraints { make in
            make.left.centerY.equalTo(countryButton)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        arrowImageView.snp.makeConstraints { make in
            make.right.centerY.equalTo(countryButton)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        
        accountLabel.snp.makeConstraints { make in
            make.left.equalTo(countryButton.snp.right).offset(12)
            make.right.equalTo(snp.right).offset(-26)
            make.height.equalTo(24)
            make.centerY.equalTo(countryButton)
        }
        
        accountLineView.snp.makeConstraints { make in
            make.bottom.left.right.equalTo(accountLabel)
            make.height.equalTo(1)
        }
        
        passwordIcon.snp.makeConstraints { make in
            make.top.equalTo(accountLineView.snp.bottom).offset(20)
            make.left.equalTo(countryButton)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        
        displayButton.snp.makeConstraints { make in
            make.centerY.equalTo(passwordIcon)
            make.right.equalTo(accountLineView)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        
        passwordTextField.snp.makeConstraints { make in
            make.left.equalTo(passwordIcon.snp.right).offset(12)
            make.right.equalTo(displayButton.snp.left).offset(-12)
            make.height.equalTo(passwordIcon)
            make.centerY.equalTo(passwordIcon)
        }
        
        passwordLineView.snp.makeConstraints { make in
            make.bottom.left.equalTo(passwordTextField)
            make.right.equalTo(displayButton)
            make.height.equalTo(accountLineView)
        }
        
        prebindingCardLabel.isHidden = !hasPrebingCard
        var top = prebindingCardLabel.isHidden ? 8 : 33
        var size = forgotButton.frame.size
        forgotButton.snp.remakeConstraints { make in
            make.left.equalTo(passwordTextField).offset(2)
            make.top.equalTo(passwordLineView.snp.bottom).offset(top.ui_mscale)
            make.width.equalTo(size.width)
            make.height.equalTo(size.height)
        }
        if !prebindingCardLabel.isHidden {
            prebindingCardLabel.snp.makeConstraints { make in
                make.left.equalTo(forgotButton)
                make.right.equalTo(passwordLineView)
                make.top.equalTo(passwordLineView.snp.bottom).offset(8.ui_mscale)
            }
        }
        
        size = signInButton.frame.size
        top = prebindingCardLabel.isHidden ? 54 : 80
        signInButton.snp.remakeConstraints { make in
            make.centerX.equalTo(contentView)
            make.top.equalTo(passwordLineView.snp.bottom).offset(top.ui_mscale)
            make.width.equalTo(size.width)
            make.height.equalTo(size.height)
        }
        
        privacyView.snp.makeConstraints { make in
            make.left.right.equalTo(signInButton)
            make.height.equalTo(84.ui_mscale)
            make.bottom.equalTo(contentView)
        }
    }
    
    func setupMakeInitialize() {
        didTapDisplay(sender: displayButton)
    }
    
    func setupMakeNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
}
